package qimao.com.edu.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;

import qimao.com.edu.config.AppConfig;
import qimao.com.edu.entity.Chapters;
import qimao.com.edu.entity.Works;
import qimao.com.edu.service.ChaptersService;
import qimao.com.edu.service.WorksService;
import qimao.com.edu.service.impl.ChaptersServiceImpl;
import qimao.com.edu.service.impl.WorksServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import qimao.com.edu.util.FileUtils;

@WebServlet("/writer/insChapters.do")
public class insChapters extends HttpServlet {

	FileUtils FileUtils = new FileUtils();
	ChaptersService cs = new ChaptersServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    // 设置请求和响应的字符编码
	    request.setCharacterEncoding("UTF-8");
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("application/json");

	    try {
	        // 读取请求中的JSON数据
	        StringBuilder jsonBuilder = new StringBuilder();
	        String line;
	        try (BufferedReader reader = request.getReader()) {
	            while ((line = reader.readLine()) != null) {
	                jsonBuilder.append(line);
	            }
	        }
	        String jsonStr = jsonBuilder.toString();
	        
	        // 检查JSON是否为空
	        if (jsonStr == null || jsonStr.trim().isEmpty()) {
	            sendErrorResponse(response, "请求内容为空");
	            return;
	        }

	        // 使用Jackson解析JSON
	        ObjectMapper objectMapper = new ObjectMapper();
	        Map<String, Object> documentData = objectMapper.readValue(jsonStr, HashMap.class);

	        // 提取字段
	        String title = (String) documentData.get("title");
	        String contentNum = (String) documentData.get("BookNum");
	        String bookName = (String) documentData.get("bookName");
	        String content = (String) documentData.get("content");
	        Integer bookId = (Integer) documentData.get("bookId");
	        Integer chapterId = (Integer) documentData.get("chapterId");

	        // 打印接收到的数据
	        System.out.println("接收到文档数据:");
	        System.out.println("标题: " + title);
	        System.out.println("内容长度: " + (content != null ? content.length() : 0) + " 字符");
	        System.out.println("书籍名称: " + bookName);
	        System.out.println("书籍ID: " + bookId);
	        System.out.println("章节ID: " + chapterId);

	        // 验证必要参数
	        if (bookId == null || chapterId == null || title == null || content == null) {
	            sendErrorResponse(response, "缺少必要参数");
	            return;
	        }

	        // 构建内容目录路径
	        Path path = Paths.get(AppConfig.UPLOAD_PATH, "novel", String.valueOf(bookId), String.valueOf(chapterId));
	        
	        // 构建完整文件路径
	        Path filePath = path.resolve("content.txt");

	        try {
	            // 确保目录存在
	            FileUtils.createDirectoryIfNotExists(path.toString());
	            
	            // 写入内容到文件
	            FileUtils.writeStringToFile(content, filePath.toString());
	        } catch (IOException e) {
	            e.printStackTrace();
	            sendErrorResponse(response, "保存文件失败: " + e.getMessage());
	            return;
	        }

	        Chapters chapters = new Chapters();
	        chapters.setChapterId(chapterId);
	        chapters.setWorkId(bookId);
	        chapters.setChapterTitle(title);
	        chapters.setContentPath(filePath.toString());
	        chapters.setWordCount(content.length());

	        // 保存到数据库
	        if(cs.addChapter(chapters, bookId) != 1) {
	            sendErrorResponse(response, "保存章节信息失败");
	            return;
	        }

	        // 返回成功响应
	        Map<String, Object> responseData = new HashMap<>();
	        responseData.put("success", true);
	        responseData.put("message", "文档保存成功");
	        responseData.put("chapterId", chapterId);
	        
	        try (PrintWriter out = response.getWriter()) {
	            out.print(objectMapper.writeValueAsString(responseData));
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	        sendErrorResponse(response, "处理请求失败: " + e.getMessage());
	    }
	}
	
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }
    
    private void sendErrorResponse(HttpServletResponse response, String message) throws IOException {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("success", false);
        responseData.put("message", message);
        
        try (PrintWriter out = response.getWriter()) {
            out.print(new ObjectMapper().writeValueAsString(responseData));
        }
    }
}